package org.common.utils.fasttest;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhouzhibing
 * @date 2024/10/30
 */
public class TestVThread3 {
    private static int VIRTUAL_THREAD_COUNT = 10;

    private CountDownLatch countDownLatch;
    private ReentrantLock reentrantLock = new ReentrantLock();

    private static TestVThread3 TEST = new TestVThread3();

    public static void main(String[] args) {

//        ExecutorService executorService = Executors.newFixedThreadPool(VIRTUAL_THREAD_COUNT);
        long startTime = System.currentTimeMillis();
//        for (int i = 0; i < VIRTUAL_THREAD_COUNT; i++) {
//            int finalIndex = i;
//            executorService.execute(() -> TestVThread3.virtualStart(finalIndex));
//        }
//
        for (int i = 0; i < VIRTUAL_THREAD_COUNT; i++) {
            TestVThread3.virtualStart(i);
        }

        TEST.await();
        long endTime = System.currentTimeMillis();
        System.out.println("main finish " + (endTime - startTime));
    }

    static void virtualStart(int index) {
        Thread.ofVirtual().name("My-Virtual-" + index).start(TEST::test);
    }

    TestVThread3() {
        countDownLatch = new CountDownLatch(VIRTUAL_THREAD_COUNT);
    }

    private void test() {
//        synchronized (this) {
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println(Thread.currentThread().getName() + " execute finish");
//            countDownLatch.countDown();
//        }

        reentrantLock.lock();
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        } finally {
            System.out.println(Thread.currentThread().getName() + " " +Thread.currentThread().getName() + " execute finish");
            countDownLatch.countDown();
            reentrantLock.unlock();
        }

    }

    private void await() {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
